import React, { useEffect, useState } from 'react';
import axios from 'axios'
import useMyReducer from '../../reduce';
import { useNavigate } from 'react-router-dom';
const Index = () => {
    const [letterMap, setLetterMap] = useState({})
    const [hotCity, setHotCity] = useState([])
    const { dispatch } = useMyReducer()
    const Navigate=useNavigate()
    const getCity = async () => {
        var res = await axios.get('http://139.196.255.165:3000/city')
        setLetterMap(res.data.res[0].letterMap)
        setHotCity(res.data.res[0].hotCities)
    }
    const handleCity = (val) => {
        dispatch({
            type: 'changeCity',
            value: val
        })
        Navigate(-1)
    }
    useEffect(() => {
        getCity()
    }, []);
    const page = {
        margin: 'auto',
        width: '750px',
    }
    return (
        <div style={page}>
            <div>
                {hotCity.map(item => { return (<button key={item.id} onClick={() => { handleCity(item.nm) }}>{item.nm}</button>) })}
            </div>
            <div>
                {
                    Object.keys(letterMap).map((item, index) => {
                        return (
                            <ul key={index}>
                                <li>
                                    <div>{item}</div>
                                    <ul>
                                        <li>{letterMap[item].map(Item => { return (<div key={Item.id} onClick={() => { handleCity(Item.nm) }}>{Item.nm}</div>) })}
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        )
                    })
                }
            </div>
        </div>
    );
}

export default Index;
